from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from .neo4j_connection import graph
from .api_instance import api_instance


class ActionAskAboutParticipateEvent(Action):
    def name(self) -> Text:
        return "action_ask_about_participate_event"

    async def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        person_name = next(tracker.get_latest_entity_values("person"), None)

        if not person_name:
            api_instance.ask(tracker.events, dispatcher)
            return []

        person_list = graph.query_person(person_name)

        if not person_list:
            dispatcher.utter_message("不好意思，我不清楚你问的" + (person_name if person_name else "") + "是谁。", attachment="finish")
            return []

        event_list = graph.query_person_participate_event(person_name)

        if not event_list:
            dispatcher.utter_message(person_name + "的生活比较平淡，暂时还没有参与什么有意思的事情。", attachment="finish")
            return []

        message = "和" + person_name + "有关的故事有：\n"

        for record in event_list:
            message += record["event"] + "\n"

        api_instance.optimize_response(tracker.events, message, dispatcher)
        return []
